using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TinyERP.Framework;
using TinyERP.Framework.Controls;
using Bamboo.Core.Data;
using Bamboo.Core.Common.Collection;


using TinyERP.ERP.Business;
using TinyERP.ERP.DTO;
using log4net;
using TinyERP.Core.View.Controls;

namespace TinyERP.View
{
    public class CustomerListForm : BaseListForm
    {
        private ILog logger = LogManager.GetLogger(typeof(CustomerListForm));
		private DataGridViewTextBoxColumn firstNameColumn;
		private DataGridViewTextBoxColumn lastNameColumn;
		private DataGridViewTextBoxColumn titleColumn;
		private DataGridViewTextBoxColumn descriptionColumn;
		private DataGridViewTextBoxColumn phoneNumberColumn;
		private DataGridViewTextBoxColumn webSiteColumn;
		private DataGridViewTextBoxColumn imColumn;
		private DataGridViewTextBoxColumn faxColumn;
		private DataGridViewTextBoxColumn primaryAddressColumn;
		private DataGridViewTextBoxColumn customerTypeColumn;

		public ICustomerService CustomerService 
		{
			get
			{
				return (ICustomerService) ServiceLocator.GetService("CustomerServiceProxy");
			}
		}

        protected override void InitSearchPanel()
        {
            this.searchBar = new CustomerSearchBar();
            this.searchBar.Dock = DockStyle.Fill;
            this.searchBar.SearchHandler = this;
            this.searchPanel.Controls.Add(this.searchBar);
        }

        protected override void LoadGridData()
        {
            string defaultSearchFieldValue = this.searchBar.SearchValue;
            if (string.IsNullOrEmpty(defaultSearchFieldValue))
            {
                LoadGridViewDefaultData(currentSortDirection, currentSortField);
                return;
            }
            CustomerSearchBar customerSearchBar = (CustomerSearchBar)searchBar;
            if (customerSearchBar.SearchBy == "FirstName" || 
                customerSearchBar.SearchBy == "LastName" ||
                customerSearchBar.SearchBy == "Email")
            {
                BuildDefaultSearchConditions();
                LoadGridViewSearchData(searchConditions, currentSortDirection, currentSortField);
                return;
            }
            else if (customerSearchBar.SearchBy == "PhoneNumber")
            {
                SearchByPhoneNumber(currentSortDirection, currentSortField);
            }
            
        }
        protected override void BuildDefaultSearchConditions()
        {
            CustomerSearchBar customerSearchBar = (CustomerSearchBar)searchBar;
            searchConditions = new List<SearchCondition>();
            SearchCondition condition = new SearchCondition();
            condition.SearchField = customerSearchBar.SearchBy;
            condition.SearchParameterName = "Name";
            condition.SearchOperator = SearchOperator.LIKE;
            string defaultSearchFieldValue = customerSearchBar.SearchValue;
            condition.SearchParameterValue = "%" + defaultSearchFieldValue + "%";
            searchConditions.Add(condition);
        }
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.firstNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.lastNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.titleColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.descriptionColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.phoneNumberColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.webSiteColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.imColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.faxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.primaryAddressColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.customerTypeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.searchPanel.SuspendLayout();
            this.bottomPanel.SuspendLayout();
            this.contentPanel.SuspendLayout();
            this.navigationPanel.SuspendLayout();
            this.SuspendLayout();
            // 
            // searchBar
            // 
            this.searchBar.Location = new System.Drawing.Point(3, 0);
            this.searchBar.Size = new System.Drawing.Size(584, 33);
            // 
            // firstNameColumn
            // 
            this.firstNameColumn.Name = "firstNameColumn";
            // 
            // lastNameColumn
            // 
            this.lastNameColumn.Name = "lastNameColumn";
            // 
            // titleColumn
            // 
            this.titleColumn.Name = "titleColumn";
            // 
            // descriptionColumn
            // 
            this.descriptionColumn.Name = "descriptionColumn";
            // 
            // phoneNumberColumn
            // 
            this.phoneNumberColumn.Name = "phoneNumberColumn";
            // 
            // webSiteColumn
            // 
            this.webSiteColumn.Name = "webSiteColumn";
            // 
            // imColumn
            // 
            this.imColumn.Name = "imColumn";
            // 
            // faxColumn
            // 
            this.faxColumn.Name = "faxColumn";
            // 
            // primaryAddressColumn
            // 
            this.primaryAddressColumn.Name = "customerAddressListColumn";
            // 
            // customerTypeColumn
            // 
            this.customerTypeColumn.Name = "customerTypeColumn";
            // 
            // CustomerListForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.ClientSize = new System.Drawing.Size(617, 298);
            this.Name = "CustomerListForm";
            this.searchPanel.ResumeLayout(false);
            this.bottomPanel.ResumeLayout(false);
            this.contentPanel.ResumeLayout(false);
            this.navigationPanel.ResumeLayout(false);
            this.navigationPanel.PerformLayout();
            this.ResumeLayout(false);
           
        }

        #endregion

        
        
        private void SetupDataGridView()
        {
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
			this.firstNameColumn
			,
			this.lastNameColumn
			,
			this.titleColumn
			,
            this.imColumn
			,
            this.phoneNumberColumn
            ,
			this.primaryAddressColumn
			,
			this.descriptionColumn
			,
			this.webSiteColumn
			,
			this.faxColumn
			,
            
			this.customerTypeColumn
            });
            
			this.firstNameColumn.DataPropertyName = "FirstName";
            this.firstNameColumn.HeaderText = "First name";
			this.firstNameColumn.Name = "firstNameColumn";
			this.firstNameColumn.Tag = "firstName";
			this.firstNameColumn.ReadOnly = true;
			this.firstNameColumn.SortMode = DataGridViewColumnSortMode.Programmatic;

			this.lastNameColumn.DataPropertyName = "LastName";
            this.lastNameColumn.HeaderText = "Last name";
			this.lastNameColumn.Name = "lastNameColumn";
			this.lastNameColumn.Tag = "lastName";
			this.lastNameColumn.ReadOnly = true;
			this.lastNameColumn.SortMode = DataGridViewColumnSortMode.Programmatic;

			this.titleColumn.DataPropertyName = "Title";
            this.titleColumn.HeaderText = "Title";
			this.titleColumn.Name = "titleColumn";
			this.titleColumn.Tag = "title";
			this.titleColumn.ReadOnly = true;
			this.titleColumn.SortMode = DataGridViewColumnSortMode.Programmatic;

			this.descriptionColumn.DataPropertyName = "Description";
            this.descriptionColumn.HeaderText = "Description";
			this.descriptionColumn.Name = "descriptionColumn";
			this.descriptionColumn.Tag = "description";
			this.descriptionColumn.ReadOnly = true;
			this.descriptionColumn.SortMode = DataGridViewColumnSortMode.Programmatic;

            this.phoneNumberColumn.DataPropertyName = "PrimaryPhone";
			this.phoneNumberColumn.HeaderText = "Primary phone";
			this.phoneNumberColumn.Name = "phoneNumberColumn";
			this.phoneNumberColumn.Tag = "phoneNumber";
			this.phoneNumberColumn.ReadOnly = true;
			this.phoneNumberColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
			this.webSiteColumn.DataPropertyName = "WebSite";
			this.webSiteColumn.HeaderText = "WebSite";
			this.webSiteColumn.Name = "webSiteColumn";
			this.webSiteColumn.Tag = "webSite";
			this.webSiteColumn.ReadOnly = true;
			this.webSiteColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
            this.imColumn.DataPropertyName = "PrimaryIM";
            this.imColumn.HeaderText = "Primary IM";
			this.imColumn.Name = "imColumn";
			this.imColumn.Tag = "im";
			this.imColumn.ReadOnly = true;
			this.imColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
			this.faxColumn.DataPropertyName = "Fax";
			this.faxColumn.HeaderText = "Fax";
			this.faxColumn.Name = "faxColumn";
			this.faxColumn.Tag = "fax";
			this.faxColumn.ReadOnly = true;
			this.faxColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
            
            this.primaryAddressColumn.DataPropertyName = "PrimaryAddress";
            this.primaryAddressColumn.HeaderText = "Primary address";
            this.primaryAddressColumn.Name = "primaryAddressColumn";
            this.primaryAddressColumn.Tag = "primaryAddress";
			this.primaryAddressColumn.ReadOnly = true;
            this.primaryAddressColumn.Width = 250;
            this.primaryAddressColumn.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            this.primaryAddressColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
			
			this.customerTypeColumn.DataPropertyName = "CustomerType";
			this.customerTypeColumn.HeaderText = "Customer type";
			this.customerTypeColumn.Name = "customerTypeColumn";
			this.customerTypeColumn.Tag = "customerType";
			this.customerTypeColumn.ReadOnly = true;
			this.customerTypeColumn.SortMode = DataGridViewColumnSortMode.NotSortable;

            this.dataGridView.AutoGenerateColumns = false;
            this.dataGridView.MultiSelect = false;
            this.dataGridView.ModuleAssemblyName = "TinyERP.ERP";
            this.dataGridView.AllowUserToOrderColumns = true;
            this.dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            InitializeSortKeyMap();
        }
        
        private void InitializeSortKeyMap() 
        {
        }

		public CustomerListForm() : base()
        {
            InitializeComponent();
            this.SetupDataGridView();
        }
        

		public override void OnNew()
        {
            CustomerEditInfoForm editForm = new CustomerEditInfoForm();
            editForm.OnNeedReloadData += delegate(object senderObj)
            {
                LoadGridData();
            };
            new DialogHelper(editForm).ShowDialog(UIManager.MainScreen);
        }
        

		public override void OnDelete()
        {
			if (this.dataGridView.SelectedRows.Count == 0)
            {
                return;
            }
            CustomerDTO customer = (CustomerDTO)this.dataGridView.SelectedRows[0].DataBoundItem;
            try 
			{
                if (MessageBox.Show(CommonMessage.GetDeleteConfirmMessage("Customer"),
                CommonMessage.GetConfirmationText(), MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
					CustomerService.DeleteCustomerByID(customer.ID);
					MessageBox.Show(CommonMessage.GetDeleteSuccessMessage("Customer"));
					LoadGridData();
				}
			}
			catch(Exception ex) 
			{
				logger.Error(ex);
				MessageBox.Show(CommonMessage.GetCanNotDeleteError("Customer"));
			}
        }
        
        
        public override void OnEdit()
        {
            if (this.dataGridView.SelectedRows == null || this.dataGridView.SelectedRows.Count == 0)
            {
                return;
            }
            CustomerDTO customerDTO = (CustomerDTO) this.dataGridView.SelectedRows[0].DataBoundItem;
            CustomerEditInfoForm editForm = new CustomerEditInfoForm();
            editForm.IsEditMode = true;
            editForm.ApplyACL(this.AllowEdit, this.AllowDelete, this.AllowCreate);
            editForm.Customer = customerDTO;
			editForm.OnNeedReloadData += delegate(object senderObj)
            {
                LoadGridData();
            };
            new DialogHelper(editForm).ShowDialog(UIManager.MainScreen);
        }
        

        

        
		protected override void LoadGridViewSearchData(IList<SearchCondition> searchConditions, Bamboo.Core.Data.SortDirection sortDirection, string columnName)
        {
			long totalRecord = 0;
            IList customerList = CustomerService.SearchCustomer(paging.CurrentPage, paging.PageSize, searchConditions, columnName, sortDirection, out totalRecord);
            this.paging.TotalRecord = totalRecord;
            if (customerList.Count == 0)
            {
                MessageBoxHelper.ShowInformation(AppResourceManager.GetInstance().GetString("ResultNotFound"));
            }
            SortableBindingList<CustomerDTO> sortableCustomerList = SortableBindingList<CustomerDTO>.CreateSortableBindingList(customerList);
            this.dataGridView.DataSource = sortableCustomerList;
        }

        protected override void LoadGridViewDefaultData(Bamboo.Core.Data.SortDirection sortDirection, string columnName) 
        {
        	long totalRecord = 0;
            IList customerList = CustomerService.GetAllCustomer(paging.CurrentPage, paging.PageSize, columnName, sortDirection, out totalRecord);
            this.paging.TotalRecord = totalRecord;
            SortableBindingList<CustomerDTO> sortableCustomerList = SortableBindingList<CustomerDTO>.CreateSortableBindingList(customerList);
            this.dataGridView.DataSource = sortableCustomerList;
        }

        protected void SearchByPhoneNumber(Bamboo.Core.Data.SortDirection sortDirection, string columnName)
        {
            long totalRecord = 0;
            IList customerList = CustomerService.SearchCustomerByPhone(this.searchBar.SearchValue, paging.CurrentPage, paging.PageSize, columnName, sortDirection, out totalRecord);
            this.paging.TotalRecord = totalRecord;
            SortableBindingList<CustomerDTO> sortableCustomerList = SortableBindingList<CustomerDTO>.CreateSortableBindingList(customerList);
            this.dataGridView.DataSource = sortableCustomerList;
        }  
    }
}
